﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using simpleHotel.Business;

namespace simpleHotel.Web
{
    /// <summary>
    /// 
    /// </summary>
    public partial class BookingInfoConfirm : BasePage
    {
        string[] paymenttype ={"Thanh toán bằng thẻ ghi nợ","Thanh toán bằng tiền mặt"};
        string sumall = string.Empty;                   
       
        protected StringBuilder data = new StringBuilder();
        protected decimal sumtotal = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Response.Write(Convert.ToDateTime(Session["CHECKINDATE"].ToString()).ToString("dd/MM/yyyy"));
                //Response.Write(Session["LOCATION"]+"");

                LoadInfo();
            }
        }

        protected void chkAgree_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAgree.Checked)
                btnPayment.Enabled = true;
            else
                btnPayment.Enabled = false;
        }

        private void LoadInfo()
        {
            // check redirected from bookinginfo.aspx
            if (Session["bookinginfo"] != null)
            {
                if (CheckInfo())
                {
                    lblCustomerName.Text = Session["CUSTOMERNAME"].ToString();
                    lblCMND.Text = Session["CMND"].ToString();
                    lblAddress.Text = Session["ADDRESS"].ToString();
                    lblPhone.Text = Session["PHONE"].ToString();
                    lblEmail.Text = Session["EMAIL"].ToString();
                    lblLocation.Text = Session["LOCATION"]+"";
                    lblHotelSelect.Text = Session["HOTELSELECT"]+"";

                    try
                    {
                        lblCheckIn.Text = string.Format("{0:dd/MM/yyyy}", Session["CHECKINDATE"]+"");
                        lblCheckOut.Text = string.Format("{0:dd/MM/yyyy}", Session["CHECKOUTDATE"] + "");
                        
                        //Convert.ToDateTime(Session["CHECKOUTDATE"] + "").ToString("dd/MM/yyyy");
                        //lblCheckIn.Text = Convert.ToDateTime(Session["CHECKINDATE"] + "").ToString("dd/MM/yyyy");
                        //lblCheckOut.Text = Convert.ToDateTime(Session["CHECKOUTDATE"] + "").ToString("dd/MM/yyyy");
                    }
                    catch(Exception ex)
                    {
                        Response.Write(ex.Message+"<br />Loi roi.");
                    }

                    if (Session["PAYMENTID"].ToString() == "1")
                        lblPaymentType.Text = paymenttype[0];
                    else if (Session["PAYMENTID"].ToString() == "2")
                        lblPaymentType.Text = paymenttype[1];

                    DataTable tb = (DataTable)Session["TBBOOKING"];

                    // lay thong tin gia phong
                    HotelBLL obj = new HotelBLL();
                    DataTable tbPrice = new DataTable();
                    tbPrice = obj.GetHotelRoomPrice(Int32.Parse(tb.Rows[0]["HotelID"]+""), Int32.Parse(tb.Rows[0]["RoomID"]+""));
                    string priceinfo = string.Empty;
                    foreach (DataRow dr in tbPrice.Rows)
                    {
                        priceinfo += "Thứ 2 - Thứ 6    :" + string.Format("{0:#,###}",Convert.ToDecimal(dr["NormalCompany"] + ""))+"<br/>";
                        priceinfo += "Thứ 7 - Chủ nhật :" + string.Format("{0:#,###}",Convert.ToDecimal(dr["WeekendCompany"]+"")) + "<br/>";
                        priceinfo += "Lễ - Tết :" + string.Format("{0:#,###}",Convert.ToDecimal(dr["HolidayCompany"] + ""));
                    }

                    foreach (DataRow dr in tb.Rows)
                    {
                        data.Append("<tr>");
                        data.Append("<td style=\"text-align:left;padding-left:5px\">" + dr["RoomName"] + "" + "</td>");
                        data.Append("<td style=\"text-align:right;padding-right:5px\">" + priceinfo + "</td>");
                        data.Append("<td style=\"text-align:right;padding-right:5px\">" + dr["NumberOfRoom"] + "" + "</td>");
                        data.Append("<td style=\"text-align:right;padding-right:5px\">" + string.Format("{0:#,###}", Convert.ToDecimal(dr["TotalPaid"] + "")) + "</td>");
                        data.Append("</tr>");

                        sumtotal += Convert.ToDecimal(dr["TotalPaid"] + "");
                    }
                    sumall = sumtotal.ToString();
                }
            }
            else
                Response.Redirect("~/Home.aspx");
        }

        protected void btnPayment_Click(object sender, EventArgs e)
        {
            


            if (CheckInfo())
            {
                BookingBLL b = new BookingBLL();
                string bookingCode = string.Empty;

                int customerID = b.InsertCustomer(Session["CUSTOMERNAME"].ToString(),
                                                  Session["CMND"].ToString(),
                                                  Session["ADDRESS"].ToString(),
                                                  Session["PHONE"].ToString(),
                                                  Session["EMAIL"].ToString());

                string statustransfer = string.Empty;

                DataTable tb = (DataTable)Session["TBBOOKING"];



                if (tb != null && tb.Rows.Count > 0)
                {
                    foreach (DataRow dr in tb.Rows)
                    {
                        bookingCode = b.GenerateBookingCode(Int32.Parse(Session["LOCATIONID"] + ""), Int32.Parse(dr["HotelID"] + ""));

                        int ID = b.InsertBookingInfo(customerID,
                                                     Int32.Parse(dr["HotelID"] + ""),
                                                     Int32.Parse(Session["PAYMENTID"].ToString()),
                                                     decimal.Parse(dr["TotalPaid"] + ""),
                                                     Convert.ToDateTime(ReplaceDate(Session["CHECKINDATE"] + "")),
                                                     Convert.ToDateTime(ReplaceDate(Session["CHECKOUTDATE"] + "")),
                                                     0,
                                                     Int32.Parse(dr["NumberOfRoom"] + ""),
                                                     Int32.Parse(dr["RoomID"] + ""),
                                                     bookingCode);

                        if (ID != 0)
                            statustransfer += ID.ToString();
                    }
                }


                if (statustransfer != string.Empty)
                    Session.Add("STATUSTRANSFER", statustransfer);

                // get infor for send email
                string toName = Session["CUSTOMERNAME"].ToString();
                string CMND = Session["CMND"].ToString();
                string address = Session["ADDRESS"].ToString();
                string phone = Session["PHONE"].ToString();
                string email = Session["EMAIL"].ToString();
                ////lblLocation.Text = Session["LOCATION"] + "";
                string hotelName = Session["HOTELSELECT"] + "";
                string checkin = Session["CHECKINDATE"] + "";
                string checkout = Session["CHECKOUTDATE"] + "";
                string roomType = string.Empty;
                string roomCount = string.Empty;
                string price = string.Empty;
                string payType = string.Empty;

                if (Session["PAYMENTID"].ToString() == "1")
                    payType = paymenttype[0];
                else if (Session["PAYMENTID"].ToString() == "2")
                    payType = paymenttype[1];

                DataTable tbBooking = (DataTable)Session["TBBOOKING"];
                foreach (DataRow dr in tbBooking.Rows)
                {
                    roomType = dr["RoomName"] + "";
                    roomCount = dr["NumberOfRoom"] + "";
                    price = string.Format("{0:#,###}", Convert.ToDecimal(dr["TotalPaid"] + "")).Replace(",", ".");
                    
                    //sumtotal += Convert.ToDecimal(dr["TotalPaid"] + "");
                }

                string subject = "HappyBooking.vn";
                AlternateView htmlView = simple.Utilities.SendMail.GetEmailViewFromTemplateTemplate(toName,CMND,address,phone,email,
                                                                                                    bookingCode,hotelName,checkin,checkout,
                                                                                                    roomType,roomCount,price,payType);

                

                // end


                if (Session["PAYMENTID"].ToString() == "1") // pay by card
                {
                    Session.Add("TRANSACTIONID", ID.ToString());

                    decimal sum = 0;
                    DataTable tbl = (DataTable)Session["TBBOOKING"];
                    foreach (DataRow dr in tb.Rows)
                    {
                        sum += Convert.ToDecimal(dr["TotalPaid"] + "");
                    }

                    // Send email to customer
                    simple.Utilities.SendMail.SendEmail(email, subject, null, htmlView);

                    ProcessOnepay(sum.ToString());
                }
                else if (Session["PAYMENTID"].ToString() == "2")
                {
                    pnlBookingInfo.Visible = false;
                    pnlMessage.Visible = true;

                    // Send email to customer
                    simple.Utilities.SendMail.SendEmail(email, subject, null, htmlView);
                }
            }
            else
            {
                Response.Write("Your session has timeout, please input information again.");
            }
        }

        /// <summary>
        /// Check session info has value
        /// </summary>
        /// <returns></returns>
        private bool CheckInfo()
        {
            bool res = false;
            if (Session["CUSTOMERNAME"] != null &&
                Session["CMND"] != null &&
                Session["ADDRESS"] != null &&
                Session["PHONE"] != null &&
                Session["EMAIL"] != null &&
                Session["PAYMENTID"] != null
               )
            {
                res = true;
            }

            return res;
        }

        private void ProcessOnepay(string sum)
        {
            string SECURE_SECRET = "A3EFDFABA8653DF2342E8DAC29B51AF0";
            // Khoi tao lop thu vien va gan gia tri cac tham so gui sang cong thanh toan
            VPCRequest conn = new VPCRequest("http://mtf.onepay.vn/onecomm-pay/vpc.op");
            conn.SetSecureSecret(SECURE_SECRET);
            // Add the Digital Order Fields for the functionality you wish to use
            // Core Transaction Fields
            conn.AddDigitalOrderField("Title", "onepay paygate");
            conn.AddDigitalOrderField("vpc_Locale", "vn");//Chon ngon ngu hien thi tren cong thanh toan (vn/en)
            conn.AddDigitalOrderField("vpc_Version", "2");
            conn.AddDigitalOrderField("vpc_Command", "pay");
            conn.AddDigitalOrderField("vpc_Merchant", "ONEPAY");
            conn.AddDigitalOrderField("vpc_AccessCode", "D67342C2");
            conn.AddDigitalOrderField("vpc_MerchTxnRef", "hpb" + DateTime.Now.Ticks.ToString());
            conn.AddDigitalOrderField("vpc_OrderInfo", "order_information");
            conn.AddDigitalOrderField("vpc_Amount", sum.ToString());
            conn.AddDigitalOrderField("vpc_Currency", "VND");
            conn.AddDigitalOrderField("vpc_ReturnURL", "http://happybooking.vn/bookingpaid.aspx");
            // Thong tin them ve khach hang. De trong neu khong co thong tin
            conn.AddDigitalOrderField("vpc_SHIP_Street01", "");
            conn.AddDigitalOrderField("vpc_SHIP_Provice", "");
            conn.AddDigitalOrderField("vpc_SHIP_City", "");
            conn.AddDigitalOrderField("vpc_SHIP_Country", "");
            conn.AddDigitalOrderField("vpc_Customer_Phone", "");
            conn.AddDigitalOrderField("vpc_Customer_Email", "");
            conn.AddDigitalOrderField("vpc_Customer_Id", "");
            // Dia chi IP cua khach hang
            conn.AddDigitalOrderField("vpc_TicketNo", "");
            // Chuyen huong trinh duyet sang cong thanh toan
            String url = conn.Create3PartyQueryString();
            Page.Response.Redirect(url);
        }

        public string ReplaceDate(string input)
        {
            string[] arr = input.Split('/');
            string res = string.Empty;
            if (arr.Length > 0)
            {
                res = arr[2] + "/" + arr[1] + "/" + arr[0];
            }

            return res;
        }
    }
}